import { View, Text } from '@tarojs/components'
import { navigateBack, getWindowInfo, getCurrentPages } from '@tarojs/taro'
import { memo, useMemo } from 'react'
import './index.scss'

interface BtNavBarProps {
  /** 标题 */
  title?: string
  /** 是否显示返回按钮，默认自动判断（首页不显示） */
  showBack?: boolean
  /** 返回按钮点击事件 */
  onBack?: () => void
  /** 右侧内容 */
  rightContent?: React.ReactNode
  /** 自定义类名 */
  className?: string
  /** 导航栏样式 */
  navStyle?: React.CSSProperties
}

// 默认导航栏样式
const defaultNavStyle: React.CSSProperties = {
  backgroundColor: '#4575C9',
  color: '#fff'
}

function BtNavBar({
  title = '',
  showBack,
  onBack,
  rightContent,
  className = '',
  navStyle = {}
}: BtNavBarProps) {
  // 获取系统信息，计算导航栏高度
  const { barHeight, statusBarHeight } = useMemo(() => {
    const sys = getWindowInfo()
    const sysStatusBarHeight = (sys.statusBarHeight || 0) * 2
    const totalBarHeight = sysStatusBarHeight + 88
    return { barHeight: totalBarHeight, statusBarHeight: sysStatusBarHeight }
  }, [])

  // 判断是否显示返回按钮
  const shouldShowBack = useMemo(() => {
    if (typeof showBack !== 'undefined') return showBack
    const pages = getCurrentPages()
    return pages.length > 1
  }, [showBack])

  const handleBack = () => {
    if (onBack) {
      onBack()
    } else {
      navigateBack()
    }
  }

  // 合并默认样式和自定义样式
  const mergedStyle = {
    ...defaultNavStyle,
    ...navStyle,
    height: `${barHeight}rpx`
  }

  return (
    <View
      className={`bt-nav-bar ${className}`}
      style={mergedStyle}
    >
      <View
        className='bt-nav-bar__status-bar'
        style={{ height: `${statusBarHeight}rpx` }}
      />
      <View className='bt-nav-bar__content'>
        {shouldShowBack && (
          <View
            className='bt-nav-bar__back'
            onClick={handleBack}
          >
            <View className='bt-nav-bar__back-icon' />
          </View>
        )}

        <Text className='bt-nav-bar__title'>{title}</Text>

        <View className='bt-nav-bar__right'>
          {rightContent}
        </View>
      </View>
    </View>
  )
}

export default memo(BtNavBar)
